package com.itic.mobile.login;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mobile.base.BaseMobileInterface;
import com.itic.system.xhcode.persistence.model.XhCode;
import com.itic.system.xhtoken.persistence.model.XhToken;
import com.itic.system.xhtoken.persistence.model.XhTokenExample;
import com.itic.system.xhuser.persistence.model.XhUser;
import com.itic.system.xhuser.persistence.model.XhUserExample;


/**
 * 现货登入接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/login")
public class LoginInterface
     extends BaseMobileInterface {
   
    /**
     * 发送验证码
     * @return
     */
    @RequestMapping(value="/send")
    @ResponseBody
    public Map<String,Object> send( HttpServletRequest request,HttpServletResponse response,String phone ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		  //产生随机的验证码
            String codeCont = "";
    	    Random r = new Random();
    	    for(int i=0;i<6;i++){
    	    	codeCont += String.valueOf(r.nextInt(10));
    	    }
    	    
    	    XhCode phoneCode = new XhCode();
	   		phoneCode.setPhone(phone);
	   		phoneCode.setCode(codeCont);
	   		phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
	   		
	   		xhCodeService.add(phoneCode);
	   		String result = sendMassageCx(phone, codeCont);
   			if( ResponseCode.SUCCESS.getCode().equals(result) ){
   				errorCode = SUCCESS_ERROR_CODE;
   	        	errorMsg = SUCCESS_ERROR_MSG;
   			}else{
   				errorCode = CODE_ERROR_CODE;
   	        	errorMsg = CODE_ERROR_MSG;
   			}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
    		logException("LoginInterface", "send", e.toString(),"用户注册发送验证码",e);
    	}
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    /**
     * 用户注册
     * @return
     */
    @RequestMapping(value="/reg")
    @ResponseBody
    public Map<String,Object> reg(HttpServletRequest request,HttpServletResponse response, String code, XhUser user ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(code) && StringHelper.isNotBlank(user.getPhone()) && StringHelper.isNotBlank(user.getPwd()) ){
    			//验证码
    		    if( verifyCode( user.getPhone(),code ) ){
    		    	String add = xhUserService.add(user);
    		    	if( ResponseCode.SUCCESS.getCode().equals(add) ){
    		    		errorCode = SUCCESS_ERROR_CODE;
    	   	        	errorMsg = SUCCESS_ERROR_MSG;
    		    	}
    		    }else{
    		    	errorCode = PHONE_CODE_ERROR_CODE;
	   	        	errorMsg = PHONE_CODE_ERROR_MSG;
    		    }
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	logException("LoginInterface", "reg", e.toString(),"用户注册",e);
    	}
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    /**
     * 用户登入
     * @return
     */
    @RequestMapping(value="/in")
    @ResponseBody
    public Map<String,Object> in(HttpServletRequest request,HttpServletResponse response, String phone, String pwd, String token ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		
    		//用户名与密码登入
    		if( (StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(pwd)) ){
    			String createToken = createToken(phone,pwd);
    			if( null != createToken ){
    				resultMap.put(DATA, createToken);
    				errorCode = SUCCESS_ERROR_CODE;
	   	        	errorMsg = SUCCESS_ERROR_MSG;
    			}else{
    				errorCode = PWD_ERROR_CODE;
	   	        	errorMsg = PWD_ERROR_MSG;
    			}
    		}
    		
    		//用户TOKEN登入
    		if( StringHelper.isNotBlank(token) && !errorCode.equals("200") ){
    			//验证TOKEN是否正确
    			XhUser user = getUserByToken(token);
    			if( null != user ){
    				resultMap.put(DATA, token);
    				errorCode = SUCCESS_ERROR_CODE;
	   	        	errorMsg = SUCCESS_ERROR_MSG;
    			}else{
    				errorCode = LOGIN_ERROR_CODE;
	   	        	errorMsg = LOGIN_ERROR_MSG;
    			}		
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
    		logException("LoginInterface", "in", e.toString(),"用户登入",e);
    	}
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    /**
     * 用户退出
     * @return
     */
    @RequestMapping(value="/out")
    @ResponseBody
    public Map<String,Object> out(HttpServletRequest request,HttpServletResponse response, String token ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//用户名与密码登入
    		if( StringHelper.isNotBlank(token) ){
    			XhUser user = getUserByToken(token);
    			if( null != user ){
    				XhTokenExample example = new XhTokenExample();
    				example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andAccessTokenEqualTo(token);
    				XhToken xhToken = new XhToken();
    				xhTokenService.deleteByExample(xhToken, example);
    			}
    			errorCode = SUCCESS_ERROR_CODE;
   	        	errorMsg = SUCCESS_ERROR_MSG;
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
    		logException("LoginInterface", "out", e.toString(),"用户退出",e);
    	}
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    /**
     * 密码找回
     * @return
     */
    @RequestMapping(value="/findPwd")
    @ResponseBody
    public Map<String,Object> findPwd(HttpServletRequest request,HttpServletResponse response, String phone, String code, String pwd ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//用户名与密码登入
    		if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) && StringHelper.isNotBlank(pwd) ){
    			//判断手机号是不是我们的用户
    			XhUser user = getUserByPhone(phone);
    			if( null != user ){
    				//判断验证码是否正确
    				if( verifyCode(phone, code) ){
    					//设置新密码
    					user.setPwd(pwd);
    					xhUserService.edit(user);
        				errorCode = SUCCESS_ERROR_CODE;
           	        	errorMsg = SUCCESS_ERROR_MSG;
    				}else{
    					errorCode = PHONE_CODE_ERROR_CODE;
           	        	errorMsg = PHONE_CODE_ERROR_MSG;
    				}
    			}else{
    				errorCode = PHONE_NULL_ERROR_CODE;
       	        	errorMsg = PHONE_NULL_ERROR_MSG;
    			}
    			
    			
    			
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
    		logException("LoginInterface", "out", e.toString(),"用户退出",e);
    	}
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    
    
    public String createToken( String phone, String pwd ){
    	String token = null ;
    	XhUserExample example = new XhUserExample();
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andPhoneEqualTo(phone).andPwdEqualTo(pwd);
    	List<XhUser> list = xhUserService.list(example);
    	if( list.size()>0 ){
    		String tmptoken = getToken();
    		XhUser user = list.get(0);
    		XhToken xhToken = new XhToken();
    		xhToken.setAccessToken(tmptoken);
    		xhToken.setExpiredTime(getExpiredTimeToken(new Date()));
    		xhToken.setUserId(user.getId());
    		String add = xhTokenService.add(xhToken);
    		if( ResponseCode.SUCCESS.getCode().equals(add) ){
    			token = tmptoken;
    		}
    	}
    	return token;
    }
}